package cmds

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var (
	CasServiceSystemd = "cas.service"
	DefaultDir        = "/root/iscas"
)

func NewResetCommand(action func(*cli.Context) error) cli.Command {
	return cli.Command{
		Name:            "reset",
		Usage:           "reset the cas cluster to its initial state",
		SkipFlagParsing: true,
		SkipArgReorder:  true,
		Action:          action,
	}
}

func ResetCasCluster(cli *cli.Context) error {

	dir, err := findDatadir()
	if err != nil {
		return err
	}

	if dir == "" {
		dir = DefaultDir
	}

	casUninstallScriptsFilePath := filepath.Join(dir, "data", "cas", "scripts", "cas-uninstall.sh")
	_, err = os.Stat(casUninstallScriptsFilePath)
	if err != nil {
		return fmt.Errorf("can't find uninstall scripts file: %s", casUninstallScriptsFilePath)
	}

	casKillAllScriptsFilePath := filepath.Join(dir, "data", "cas", "scripts", "cas-killall.sh")
	_, err = os.Stat(casKillAllScriptsFilePath)
	if err != nil {
		return fmt.Errorf("can't find kill cas process scripts file: %s", casKillAllScriptsFilePath)
	}

	output, err := executeScript(casUninstallScriptsFilePath)
	if err != nil {
		return err
	}
	logrus.Info(output)
	return nil
}

func findDatadir() (string, error) {

	//serviceName := CasSystemdFile
	cmd := exec.Command("systemctl", "show", "--property=ExecStart", CasServiceSystemd)
	var out bytes.Buffer
	cmd.Stdout = &out
	errfun := cmd.Run
	if errfun() != nil {
		logrus.Errorf("Error running systemctl command:%v", errfun())
		return "", errfun()
	}

	execStart := out.String()
	if strings.Contains(execStart, "--data-dir=") {
		start := strings.Index(execStart, "--data-dir=")
		substr := execStart[start:]
		fields := strings.Fields(substr)
		for _, field := range fields {
			if strings.Contains(field, "--data-dir=") {
				rel := strings.Replace(field, "--data-dir=", "", -1)
				return rel, nil
			}
		}
	}

	if strings.Contains(execStart, "-d=") {
		start := strings.Index(execStart, "-d=")
		substr := execStart[start:]
		fields := strings.Fields(substr)
		for _, field := range fields {
			if strings.Contains(field, "-d=") {
				rel := strings.Replace(field, "-d=", "", -1)
				return rel, nil
			}
		}
	}

	return "", nil
}

func executeScript(scriptPath string, args ...string) (output string, err error) {
	cmd := exec.Command("/bin/bash", append([]string{scriptPath}, args...)...)
	var out bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &out

	err = cmd.Run()
	output = out.String()
	return
}
